
package com.shop.cloud.mall.admin.controller;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.cloud.common.core.constant.CommonConstants;
import com.shop.cloud.common.core.constant.SecurityConstants;
import com.shop.cloud.common.core.util.R;
import com.shop.cloud.common.log.annotation.SysLog;
import com.shop.cloud.common.security.entity.BaseUser;
import com.shop.cloud.common.security.util.SecurityUtils;
import com.shop.cloud.mall.admin.service.*;
import com.shop.cloud.mall.common.constant.MallConstants;
import com.shop.cloud.mall.common.dto.OrderDeliveryDTO;
import com.shop.cloud.mall.common.entity.*;
import com.shop.cloud.mall.common.feign.FeignOrderInfoApiService;
import com.shop.cloud.weixin.common.feign.FeignWxAppService;
import com.shop.cloud.weixin.common.entity.WxApp;
import io.swagger.v3.oas.annotations.Operation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;
import org.springframework.security.access.prepost.PreAuthorize;
import io.swagger.v3.oas.annotations.tags.Tag;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 商城订单
 *
 * @author
 * @date 2019-09-10 15:21:22
 */
@Slf4j
@RestController
@AllArgsConstructor
@RequestMapping("/orderinfo")
@Tag(description = "orderinfo", name = "商城订单管理")
public class OrderInfoController {

    private final OrderInfoService orderInfoService;
	private final UserInfoService userInfoService;
	private final FeignWxAppService feignWxAppService;
	private final OrderBillService orderBillService;
	private final FeignOrderInfoApiService feignOrderInfoApiService;
	private final OrderItemService orderItemService;

    /**
    * 分页查询
    * @param page 分页对象
    * @param orderInfo 商城订单
    * @return
    */
	@Operation(summary = "分页查询")
    @GetMapping("/page")
    @PreAuthorize("@ato.hasAuthority('mall:orderinfo:index')")
    public R getPage(Page page, OrderInfo orderInfo) {
		if(StrUtil.isBlank(orderInfo.getDeliveryWay())){
			orderInfo.setDeliveryWay(MallConstants.DELIVERY_WAY_1 + "," + MallConstants.DELIVERY_WAY_2);
		}
		BaseUser baseUser = SecurityUtils.getUser();
		if(CommonConstants.USER_TYPE_3.equals(baseUser.getType())){
			//供应商
			String supplierId = baseUser.getSupplierId();
			return R.ok(orderInfoService.page2(page, Wrappers.query(orderInfo), supplierId));
		}
        return R.ok(orderInfoService.page1(page, Wrappers.query(orderInfo)));
    }

	/**
	 * 查询数量
	 * @param orderInfo
	 * @return
	 */
	@Operation(summary = "查询数量")
	@GetMapping("/count")
	@PreAuthorize("@ato.hasAuthority('mall:orderinfo:count')")
	public R getCount(OrderInfo orderInfo) {
		if(StrUtil.isBlank(orderInfo.getDeliveryWay())){
			return R.ok(orderInfoService.count(Wrappers.query(orderInfo).in("delivery_way", Convert.toList(MallConstants.DELIVERY_WAY_1 + "," + MallConstants.DELIVERY_WAY_2))));
		}
		BaseUser baseUser = SecurityUtils.getUser();
		if(CommonConstants.USER_TYPE_3.equals(baseUser.getType())){
			//供应商
			String supplierId = baseUser.getSupplierId();
			return R.ok(orderInfoService.page2(new Page<>(), Wrappers.query(orderInfo), supplierId).getTotal());
		}
		return R.ok(orderInfoService.count(Wrappers.query(orderInfo)));
	}

    /**
    * 通过id查询商城订单
    * @param id
    * @return R
    */
	@Operation(summary = "通过id查询商城订单")
    @GetMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('mall:orderinfo:get')")
    public R getById(@PathVariable("id") String id){
		OrderInfo orderInfo;
		BaseUser baseUser = SecurityUtils.getUser();
		if(CommonConstants.USER_TYPE_3.equals(baseUser.getType())){
			orderInfo = orderInfoService.getById(id);
			//供应商
			List<OrderItem> listOrderItem = orderItemService.list(Wrappers.<OrderItem>query().lambda()
					.eq(OrderItem::getOrderId,orderInfo.getId()));
			orderInfo.setListOrderItem(listOrderItem);
		}else{
			orderInfo = orderInfoService.getById1(id);
		}
		if(orderInfo.getAppType().equals(MallConstants.CLIENT_TYPE_MA) ||
				orderInfo.getAppType().equals(MallConstants.CLIENT_TYPE_H5_WX)){
			R<WxApp> r2 = feignWxAppService.getById(orderInfo.getAppId(), SecurityConstants.FROM_IN);
			orderInfo.setApp(r2.getData());
		}
		orderInfo.setUserInfo(userInfoService.getById(orderInfo.getUserId()));
		orderInfo.setOrderBill(orderBillService.getOne(Wrappers.<OrderBill>query().lambda().eq(OrderBill::getOrderId, orderInfo.getId())));
        return R.ok(orderInfo);
    }

	/**
	 * 查询统计付款金额
	 * @param orderInfo
	 * @return R
	 */
	@Operation(summary = "查询统计付款金额")
	@GetMapping("/paymentprice/sum")
	@PreAuthorize("@ato.hasAuthority('mall:orderinfo:get')")
	public R sumPaymentPrice(OrderInfo orderInfo){
		return R.ok(orderInfoService.sumPaymentPrice(orderInfo));
	}

    /**
    * 修改商城订单
    * @param orderInfo 商城订单
    * @return R
    */
	@Operation(summary = "修改商城订单")
    @SysLog("修改商城订单")
    @PutMapping
    @PreAuthorize("@ato.hasAuthority('mall:orderinfo:edit')")
    public R updateById(@RequestBody OrderInfo orderInfo){
        return R.ok(orderInfoService.updateById(orderInfo));
    }

    /**
    * 通过id删除商城订单
    * @param id
    * @return R
    */
	@Operation(summary = "通过id删除商城订单")
    @SysLog("删除商城订单")
    @DeleteMapping("/{id}")
    @PreAuthorize("@ato.hasAuthority('mall:orderinfo:del')")
    public R removeById(@PathVariable String id){
        return R.ok(orderInfoService.removeById(id));
    }

	/**
	 * 修改商城订单价格
	 * @param orderItem
	 * @return R
	 */
	@Operation(summary = "修改商城订单价格")
	@SysLog("修改商城订单价格")
	@PutMapping("/editPrice")
	@PreAuthorize("@ato.hasAuthority('mall:orderinfo:edit')")
	public R editPrice(@RequestBody OrderItem orderItem){
		orderInfoService.editPrice(orderItem);
		return R.ok();
	}

	/**
	 * 取消商城订单
	 * @param id 商城订单
	 * @return R
	 */
	@Operation(summary = "取消商城订单")
	@SysLog("取消商城订单")
	@PutMapping("/cancel/{id}")
	@PreAuthorize("@ato.hasAuthority('mall:orderinfo:edit')")
	public R orderCancel(@PathVariable String id){
		OrderInfo orderInfo = orderInfoService.getById(id);
		if(!MallConstants.DELIVERY_WAY_1.equals(orderInfo.getDeliveryWay())
				&& !MallConstants.DELIVERY_WAY_2.equals(orderInfo.getDeliveryWay())){
			return R.failed("非法配送方式");
		}
		return feignOrderInfoApiService.orderCancelInside(id, SecurityConstants.FROM_IN);
	}

	/**
	 * 商城订单自提
	 * @param id 商城订单ID
	 * @return R
	 */
	@Operation(summary = "商城订单自提")
	@PutMapping("/takegoods/{id}")
	@PreAuthorize("@ato.hasAuthority('mall:orderinfo:edit')")
	public R takeGoods(@PathVariable String id){
		orderInfoService.takeGoods(id);
		return R.ok();
	}

	/**
	 * 发货商城订单
	 * @param orderDeliveryDTO 订单发货参数
	 * @return R
	 */
	@Operation(summary = "发货商城订单")
	@SysLog("发货商城订单")
	@PutMapping("/delivery")
	@PreAuthorize("@ato.hasAuthority('mall:orderinfo:edit')")
	public R delivery(@RequestBody OrderDeliveryDTO orderDeliveryDTO){
		orderInfoService.delivery(orderDeliveryDTO);
		return R.ok();
	}

	/**
	 * 查询统计
	 * @param orderInfo
	 * @return
	 */
	@Operation(summary = "查询统计")
	@GetMapping("/statistics")
	@PreAuthorize("@ato.hasAuthority('mall:orderinfo:statistics')")
	public R getStatistics(OrderInfo orderInfo) {
		if(StrUtil.isNotBlank(SecurityUtils.getUser().getShopId())){
			orderInfo.setShopId(SecurityUtils.getUser().getShopId());
		}
		//总数量
		long countTotal = orderInfoService.count(Wrappers.query(orderInfo));
		//今天数量
		LocalDate localDate = LocalDateTime.now().toLocalDate();
		long countToday = orderInfoService.count(Wrappers.query(orderInfo).between("create_time", LocalDateTime.of(localDate, LocalTime.MIN), LocalDateTime.of(localDate, LocalTime.MAX)));
		Map<String, Object> rs = new HashMap<>();
		rs.put("countTotal",countTotal);
		rs.put("countToday",countToday);
		return R.ok(rs);
	}

	/**
	 * 查询统计（根据某字段分组）
	 * @param orderInfo
	 * @return
	 */
	@Operation(summary = "查询统计（根据某字段分组）")
	@GetMapping("/statistics/{column}")
	@PreAuthorize("@ato.hasAuthority('mall:orderinfo:statistics')")
	public R getStatisticsByColumn(@PathVariable("column") String column, OrderInfo orderInfo) {
		if(StrUtil.isNotBlank(SecurityUtils.getUser().getShopId())){
			orderInfo.setShopId(SecurityUtils.getUser().getShopId());
		}
		List<Map<String, Object>> appTypeMapList= orderInfoService.listMaps(Wrappers.query(orderInfo)
				.select(column + " as name, count(*) as value")
				.groupBy(column)
				.orderByAsc(column));
		return R.ok(appTypeMapList);
	}

}
